package com.examples.startservice;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {
	// Handler for callbacks to the UI thread
    final Handler handler = new Handler();
    WorkerTask workerTask = new WorkerTask();

	
	@Override
	public void onCreate() {
		Toast.makeText(this, "Create service", Toast.LENGTH_SHORT).show();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Toast.makeText(this, "Start service", Toast.LENGTH_SHORT).show();

		// Execute worker task
		workerTask.execute();
		
		// If we get killed, after returning from here, restart
		return START_STICKY;
	}

	@Override
	public IBinder onBind(Intent intent) {
		// We don't provide binding, so return null
		return null;
	}

	@Override
	public void onDestroy() {
		Toast.makeText(this, "Destroy service", Toast.LENGTH_SHORT).show();
		
		if (!workerTask.isCancelled()) {
			workerTask.cancel(true);
		}
	}

	/*
	 * Do threaded work in an AsyncTask, makes posting result back on UI-thread easy
	 * Params = Type of input parameters to background thread
	 * Progress = Type of progress units
	 * Result = Type of result from the background computation  
	 */
	private class WorkerTask extends AsyncTask<Void, String, String> {

		@Override
		protected String doInBackground(Void... params) {
			// Take care of input params
			// Void nothing = params[0];
			
			// Do some heavy computing right here somewhere
			try {
				Thread.sleep(5000);
				
				// Check if we have been canceled
				if (!isCancelled()) {
					// Not canceled, Publish progress and keep going
					publishProgress("Halfway there!");
				
					Thread.sleep(5000);
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return "We are done!";
		}
		
		@Override
		protected void onProgressUpdate(String... values) {
			// This is on the UI-thread. Display progress
			Toast.makeText(MyService.this, values[0], Toast.LENGTH_SHORT).show();
		}

		@Override
		protected void onPostExecute(String result){
			// Back on the UI-thread, post results
			Toast.makeText(MyService.this, result, Toast.LENGTH_SHORT).show();
			
			// Our work is done here, stop service
			stopSelf();
		}
		
		@Override
		protected void onCancelled() {
			// This will be called instead of onPostExecute if
			// the task was canceled
			Toast.makeText(MyService.this, "You canceled the task so no result for you", Toast.LENGTH_SHORT).show();
		}
	}
}